package bi.uc.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.StringWriter;
import java.net.Socket;
import java.net.SocketTimeoutException;

import org.xmlpull.v1.XmlSerializer;
import bi.uc.login.Info;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.util.Xml;

public class SocketService extends Service{     
	Socket socket = null; 
	Info info = Info.getInfo();
	boolean hasBox = false;
	/* (non-Javadoc)
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		((ExitApplication)getApplication()).addService(this);
		Log.e("tag", "onCreate-service");
	}

	@Override
	
	public int onStartCommand(Intent intent, int flags, int startId) {
//		int startCmdResult = super.onStartCommand(intent, flags, startId);
		Log.e("tag", "onStartCommand");
		new Thread(new Runnable() {
			@Override
			public void run() {
				initLogin();
			}
		}).start();		
		return START_NOT_STICKY;
	}
/**
	 * 
	 */
	private void initLogin() {
		// TODO Auto-generated method stub
		Log.e("tag", "initLogin");
//		String mLinkMsg = "<MESSAGE action=\"InitUser\" group=\""+info.employID+"\" uid=\"aOperator"+info.userID+"\" uname=\""+info.userName+"\"/>";
		int flag0 = 0;
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter Msg = new StringWriter();
		try {
//			serializer.startDocument("UTF-8", true);
			serializer.setOutput(Msg);
			serializer.startTag("", "MESSAGE");
			serializer.attribute("", "action", "InitUser");
			serializer.attribute("", "group", info.employID);
			serializer.attribute("", "uid", "aOperator"+info.userID);
			Log.d("tag", info.userName);
			serializer.attribute("", "uname", info.userName);
			serializer.endTag("", "MESSAGE");
			serializer.endDocument();
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Log.e("send", Msg.toString());

		while (true) {

			try {	
				socket = new Socket("bi.bi-uc.com", 6789);
				OutputStream os = socket.getOutputStream();
				os.write(Msg.toString().getBytes("UTF-8"));
//				os.close();
				socket.setSoTimeout(1000);
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						CheckIsAlive();
					}
				}).start();
				
				new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						TCPevent();
					}
				}).start();
				break;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				//创建输出流时发生 I/O 错误或者没有连接套接字
				if (++flag0>3) {
//					socket.close();
					((ExitApplication)getApplication()).exitBox("客户端无法连接服务器，请确认网络已连接！");
					break;
				}
				e.printStackTrace();
			}
					
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}

	private void TCPevent() {
		String mReceivedMsg = null;
		while (true) {
			try {			

				BufferedReader reader = new BufferedReader(new InputStreamReader(
						socket.getInputStream()));
				mReceivedMsg = reader.readLine();
				Log.d("在别处登录", mReceivedMsg);
				hasBox = true;
				socket.close();				
				((ExitApplication)getApplication()).exitBox("您的帐号在其他地方登录,您将被迫下线.对您造成的不便敬请谅解！");
				break;
			} catch (SocketTimeoutException e) {
//				Log.e("socket", "SocketTimeout");
//				e.printStackTrace();
			} catch (Exception e) {
				if (hasBox) {
					break;
				}
				e.printStackTrace();				
			}
						
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	

	private void CheckIsAlive() {
		int flag = 0;
//		String mSendMsg = "<MESSAGE action=\"InitUser\" group=\""+info.employID+"\" uid=\"aOperator"+info.userID+"\" uname=\""+info.userName+"\"/>";
		XmlSerializer serializer = Xml.newSerializer();
		StringWriter mLinkMsg = new StringWriter();
		try {
			serializer.setOutput(mLinkMsg);
			serializer.startTag("", "MESSAGE");
			serializer.attribute("", "action", "InitUser");
			serializer.attribute("", "group", info.employID);
			serializer.attribute("", "uid", "aOperator"+info.userID);
			serializer.attribute("", "uname", info.userName);		
			
			serializer.attribute("", "touid", "aOperator"+info.userID);
			serializer.attribute("", "touname", "##check##");
			serializer.attribute("", "body", "");
			serializer.endTag("", "MESSAGE");
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalStateException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	
		while (true) {
			try {			
				OutputStream os = socket.getOutputStream();
				os.write(mLinkMsg.toString().getBytes("UTF-8"));
//				os.close();
//				PrintWriter writer = new PrintWriter(new BufferedWriter(
//						new OutputStreamWriter(socket.getOutputStream())));
//				writer.println(mLinkMsg.toString());
//				writer.flush();	
			} catch (IOException e) {
				Log.e("tag", "您与服务器的连接已经断开!");
				// TODO Auto-generated catch block
				//创建输出流时发生 I/O 错误或者没有连接套接字
				e.printStackTrace();
				if (hasBox) {
					break;
				}
				if (++flag>3) {
					hasBox = true;
					((ExitApplication)getApplication()).exitBox("您与服务器已经断开连接!");
					break;
				}
				
			}
						
			try {
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		hasBox = true;
		super.onDestroy();
		Log.e("tag", "onDestroy");
	}
}
